package com.Socket;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import net.sf.json.JSONObject;

@ServerEndpoint("/websocket/{username}")
public class WebSocket {

	private static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	private static int onlineCount = 0;
	private static Map<String, WebSocket> clients = new ConcurrentHashMap<String, WebSocket>();
	private static List<String> list = new ArrayList<String>();
	private Session session;
	private JSONObject json;
	private String username;

	@OnOpen
	public void onOpen(@PathParam("username") String username, Session session) {

		this.username = username;
		this.session = session;
		addOnlineCount();
		list.add(username);
		json = new JSONObject();
		json.element("onlineCount", getOnlineCount());
		json.element("onstatus", 1);
		json.element("list", list);
		json.element("username", username);
		json.element("head", username + "\t" + sdf.format(new Date()));
		clients.put(username, this);
		onMessage(json.toString());
		json.element("onstatus", 0);
	}

	@OnClose
	public void onClose() {
		json.element("onstatus", -1);
		list.remove(username);
		clients.remove(username);
		subOnlineCount();
		json.element("onlineCount", getOnlineCount());
		json.element("list", list);
		onMessage(json.toString());
	}

	@OnMessage
	public void onMessage(String message) {

		json.element("message", message);

		for (WebSocket item : clients.values()) {
			try {
				item.sendMessage(json.toString());
			} catch (IOException e) {
				e.printStackTrace();
				continue;
			}
		}
	}

	@OnError
	public void onError(Session session, Throwable error) {
		error.printStackTrace();
	}

	public void sendMessage(String message) throws IOException {
		// session.getBasicRemote().sendText(message);
		session.getAsyncRemote().sendText(message);
	}

	public static synchronized int getOnlineCount() {
		return onlineCount;
	}

	public static synchronized void addOnlineCount() {
		WebSocket.onlineCount++;
	}

	public static synchronized void subOnlineCount() {
		WebSocket.onlineCount--;
	}

	public static synchronized Map<String, WebSocket> getClients() {
		return clients;
	}
}
